<template>
  <div class="points-container">
    <div class="points-header">
      <div class="points-card">
        <div class="points-info">
          <h2>我的积分</h2>
          <div class="points-number">{{ userPoints }}</div>
          <div class="points-desc">当前可用积分</div>
        </div>
        <div class="points-icon">
          <trophy-outlined />
        </div>
      </div>
    </div>

    <div class="points-content">
      <a-tabs v-model:activeKey="activeTab">
        <a-tab-pane key="history" tab="积分记录">
          <a-table
            :columns="columns"
            :data-source="pointsHistory"
            :pagination="pagination"
            :loading="loading"
            row-key="id"
            @change="handleTableChange"
          >
            <template #bodyCell="{ column, record }">
              <template v-if="column.key === 'points'">
                <span
                  :class="
                    record.points > 0
                      ? 'points-plus'
                      : record.points < 0
                      ? 'points-minus'
                      : ''
                  "
                >
                  {{ record.points > 0 ? "+" : "" }}{{ record.points }}
                </span>
              </template>
              <template v-if="column.key === 'type'">
                <a-tag :color="getTypeColor(record.type)">
                  {{ getTypeText(record.type) }}
                </a-tag>
              </template>
            </template>
          </a-table>
        </a-tab-pane>
        <a-tab-pane key="rules" tab="积分规则">
          <div class="rules-content">
            <h3>积分获取规则</h3>
            <ul>
              <li>每日签到：+5积分</li>
              <li>完成知识竞赛：+10积分</li>
              <li>参与服饰知识挑战：+200积分</li>
              <li>挑战排名第一：+1000积分</li>
              <li>发表评论：+2积分</li>
              <li>购买商品：消费金额×0.1积分</li>
            </ul>
            <h3>积分使用规则</h3>
            <ul>
              <li>100积分可抵扣1元</li>
              <li>单次最多使用1000积分</li>
              <li>积分有效期为一年</li>
            </ul>
          </div>
        </a-tab-pane>
      </a-tabs>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from "vue";
import { TrophyOutlined } from "@ant-design/icons-vue";
import type { TableColumnsType } from "ant-design-vue";
import { message } from "ant-design-vue";
import { getUserPointsInfoUsingGet } from "@/api/userController";

interface PointsRecord {
  id: string;
  userId: string;
  points: number;
  type: number;
  description: string;
  createdAt: string;
}

const userPoints = ref(0);
const activeTab = ref("history");
const loading = ref(false);
const pointsHistory = ref<PointsRecord[]>([]);
const pagination = ref({
  current: 1,
  pageSize: 3,
  total: 0,
});

// 积分历史记录表格列定义
const columns: TableColumnsType = [
  {
    title: "时间",
    dataIndex: "createdAt",
    key: "time",
    customRender: ({ text }: { text: string }) => formatDateTime(text),
  },
  {
    title: "类型",
    dataIndex: "type",
    key: "type",
  },
  {
    title: "积分变动",
    dataIndex: "points",
    key: "points",
  },
  {
    title: "说明",
    dataIndex: "description",
    key: "description",
  },
];

// 格式化日期时间
const formatDateTime = (dateTimeStr: string) => {
  if (!dateTimeStr) return "";
  const date = new Date(dateTimeStr);
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, "0");
  const day = String(date.getDate()).padStart(2, "0");
  const hours = String(date.getHours()).padStart(2, "0");
  const minutes = String(date.getMinutes()).padStart(2, "0");
  const seconds = String(date.getSeconds()).padStart(2, "0");

  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
};

// 获取积分类型对应的颜色
const getTypeColor = (type: number) => {
  const colors: Record<number, string> = {
    1: "blue", // 签到
    2: "green", // 竞赛
    3: "orange", // 购物
    4: "purple", // 系统
    5: "red", // 奖励
  };
  return colors[type] || "default";
};

// 获取积分类型对应的文本
const getTypeText = (type: number) => {
  const typeTexts: Record<number, string> = {
    1: "签到",
    2: "竞赛",
    3: "购物",
    4: "系统",
    5: "奖励",
  };
  return typeTexts[type] || "其他";
};

// 加载用户积分信息
const loadUserPointsInfo = async () => {
  try {
    loading.value = true;
    const res = await getUserPointsInfoUsingGet();

    if (res.data?.code === 0 && res.data.data) {
      userPoints.value = res.data.data.totalPoints || 0;
      if (
        res.data.data.recentRecords &&
        Array.isArray(res.data.data.recentRecords)
      ) {
        pointsHistory.value = res.data.data.recentRecords;
        pagination.value.total = pointsHistory.value.length;
      }
    } else {
      message.error(res.data?.message || "获取积分信息失败");
    }
  } catch (error) {
    console.error("获取积分信息失败:", error);
    message.error("获取积分信息失败");
  } finally {
    loading.value = false;
  }
};

// 处理页面变化
const handleTableChange = (pag: any) => {
  pagination.value.current = pag.current;
};

onMounted(() => {
  loadUserPointsInfo();
});
</script>

<style scoped>
.points-container {
  padding: 20px;
}

.points-header {
  margin-bottom: 24px;
}

.points-card {
  background: linear-gradient(135deg, #8c4b3c, #a5683c);
  border-radius: 12px;
  padding: 24px;
  color: white;
  display: flex;
  justify-content: space-between;
  align-items: center;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.points-info h2 {
  margin: 0;
  font-size: 20px;
  font-weight: 500;
}

.points-number {
  font-size: 36px;
  font-weight: bold;
  margin: 12px 0;
}

.points-desc {
  font-size: 14px;
  opacity: 0.8;
}

.points-icon {
  font-size: 48px;
  opacity: 0.8;
}

.points-content {
  background: white;
  border-radius: 8px;
  padding: 24px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.points-plus {
  color: #52c41a;
  font-weight: bold;
}

.points-minus {
  color: #ff4d4f;
  font-weight: bold;
}

.rules-content {
  padding: 20px;
}

.rules-content h3 {
  color: #333;
  margin-bottom: 16px;
  font-size: 18px;
}

.rules-content ul {
  list-style: none;
  padding: 0;
  margin-bottom: 24px;
}

.rules-content li {
  padding: 8px 0;
  color: #666;
  border-bottom: 1px dashed #f0f0f0;
}

.rules-content li:last-child {
  border-bottom: none;
}

@media (max-width: 768px) {
  .points-card {
    padding: 20px;
  }

  .points-number {
    font-size: 28px;
  }

  .points-icon {
    font-size: 36px;
  }
}
</style>
